package org.example.spring.service.userServiceImpl;

import org.example.spring.context.BaseContext;
import org.example.spring.domain.dto.OrderDetailDTO;
import org.example.spring.domain.pojo.Flower;
import org.example.spring.mapper.CartMapper;
import org.example.spring.mapper.FlowerMapper;
import org.example.spring.mapper.OrderDetailMapper;
import org.example.spring.domain.pojo.OrderDetail;
import org.example.spring.service.OrderDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

@Service
public class OrderDetailServiceImpl implements OrderDetailService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private FlowerMapper flowerMapper;
    @Autowired
    private CartMapper cartMapper;


    @Override
    public ArrayList<OrderDetailDTO> getOrderDetailByOrderId(Integer orderId) {
        ArrayList<OrderDetail> orderDetails = orderDetailMapper.getOrderDetailByOrderId(orderId);
        ArrayList<Integer> flowerIds = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            flowerIds.add(orderDetail.getFlowerId());
        }
        ArrayList<Flower> flowers = flowerMapper.getFlowerByIds(flowerIds);
        ArrayList<OrderDetailDTO> orderDetailDTOS = new ArrayList<>();
        for (int i = 0; i < orderDetails.size(); i++) {
            OrderDetail orderDetail = orderDetails.get(i);
            OrderDetailDTO orderDetailDTO = OrderDetailDTO.builder()
                    .orderDetailId(orderDetail.getOrderDetailId())
                    .orderId(orderDetail.getOrderId())
                    .flowerId(orderDetail.getFlowerId())
                    .quantity(orderDetail.getQuantity())
                    .price(orderDetail.getPrice())
                    .flowerName(flowers.get(i).getName())
                    .imgUrl(flowers.get(i).getImageUrl())
                    .build();
            orderDetailDTOS.add(orderDetailDTO);
        }
        return orderDetailDTOS;
    }


    @Override //添加订单详情
    @Transactional
    public void addOrderDetail(ArrayList<OrderDetail> orderDetailList) {
        orderDetailMapper.addOrderDetail(orderDetailList);
        Integer userId = BaseContext.getCurrentId();
        for (OrderDetail orderDetail : orderDetailList) {
            Integer flowerId = orderDetail.getFlowerId();
            cartMapper.deleteCart(flowerId, userId);
        }
    }


}
